package cn.terrence.myrpc.common.rpc.server.bs;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import cn.terrence.myrpc.common.rpc.common.Request;
import cn.terrence.myrpc.common.rpc.common.Response;

/**
 * 模拟 耗时的业务（IO操作，比如请求数据库等等）
 * 本例作为实例代码，没有对其进行详细模拟
 * @author dingwei2
 *
 */
public class ServiceExecutor {
	
	public static final Map<String, String> serversMap;
	
	static {
		serversMap = new HashMap<String, String>();
		serversMap.put("Lini.TopicService.sendTopic", "S01");
		serversMap.put("Lini.TopicService.topics", "S02");
	}
	
	
	/**
	 * 服务执行,这里主要是简单模拟一下服务的调用
	 * @param request
	 * @return
	 */
	public static Response executor(Request request) {
		System.out.println("ServiceExecutor 业务执行中。。。。");
		Response result = new Response();
		try {
			Random r = new Random();
			try {
				Thread.sleep(r.nextInt(3) * 1000); //模拟耗时的IO操作
			} catch(Throwable e2){}
			String service = request.getService();
			System.out.println("服务端收到的服务调用信息：" + request.getService());
			if(serversMap.containsKey(service)) {
				Date d = new Date(System.currentTimeMillis());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				result.setRequestId(request.getRequestId());
				result.setCode((short)0);
				result.setData("{\"serverType\":\"" + serversMap.get(service)+ "\",\"params\":\"" + request.getParams()+ "\",\"responseDate\":\"" + sdf.format(d) + "\"}");
			} else {
				result.setRequestId(request.getRequestId());
				result.setCode((short)101);
			}
			return result;
		} catch(Throwable e) {
			e.printStackTrace();
			result.setCode((short)1);
		}
		return result;
	}
	

}
